package com.zhengyisky.comsumer;

import cn.hutool.core.util.RandomUtil;
import com.rabbitmq.client.Channel;
import com.zhengyisky.pojo.Order;
import com.zhengyisky.service.PurchaseService;
import com.zhengyisky.utils.SendMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;

@Component
@RabbitListener(queues = "delay-queue-2112a")
@Slf4j
public class DelayConsumer {

    @Autowired
    private PurchaseService purchaseService;

    @RabbitHandler
    public void consumer(Order order, Channel channel, Message message) throws Exception {
        log.info("收到延迟消息，当前时间:{}, 数据:{}", new Date(), order);

        //根据订单编号查询订单状态
        Order newOrder = purchaseService.findOrderById(order.getId());
        if(newOrder.getStatus() == 1){
            //延迟10秒后，还没有审批，发短信
            log.info("订单超时未审批，编号为:{}",order.getId());

            //发短信
            String code = RandomUtil.randomNumbers(6);
            SendMessage.sendSms("18500240660",code);


        }else{
            log.info("订单按时完成审批，编号为:{}",order.getId());
        }

        channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
    }
}
